package com.hzwq.demo2.role.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzwq.demo2.permission.entity.Permission;
import com.hzwq.demo2.role.entity.Role;
import com.hzwq.demo2.role.mapper.RoleMapper;
import com.hzwq.demo2.rolepermission.entity.RolePermission;
import com.hzwq.demo2.rolepermission.service.IRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhaochunlin
 * @since 2020-08-13
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    IRolePermissionService rolePermissionService;

    @Override
    public List<Role> listByUserId(Integer userId) {
        return roleMapper.listByUserId(userId);
    }

    @Override
    public Role getById(Serializable id) {
        Role role = super.getById(id);
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<RolePermission>();
        queryWrapper.eq("role_id", id);
        List<RolePermission> rolePermissionList = rolePermissionService.list(queryWrapper);
        role.setRolePermissionList(rolePermissionList);
        return role;
    }

    @Override
    public void saveRoleAndPermission(Role role) {
        if (role.getId() != null) {
            role.setUpdateTime(new Date());
        } else {
            role.setInsertTime(new Date());
        }
        super.saveOrUpdate(role);

        QueryWrapper<RolePermission> wrapper = new QueryWrapper<RolePermission>();
        wrapper.eq("role_id", role.getId());
        rolePermissionService.remove(wrapper);
        if (role != null && role.getRolePermissionList() != null && role.getRolePermissionList().size() > 0) {
            List<RolePermission> rolePermissionList = role.getRolePermissionList();
            for (RolePermission rolePermission : rolePermissionList) {
                rolePermission.setRoleId(role.getId());
            }
            rolePermissionService.saveBatch(rolePermissionList);
        }

    }

    @Override
    public int selectCountById(Integer id) {
        int  i= roleMapper.selectCountById(id);
        return i;
    }

    @Override
    public List<Permission> selectUrl(Integer id) {

        List<Permission> permissionList= roleMapper.selectUrl(id);

        return permissionList;
    }

}
